<template>
  <div class="tinymce-img-upload">
    <NUpload
      name="file"
      @change="handleChange"
      :action="uploadUrl"
      :showFileList="false"
      accept=".jpg,.jpeg,.gif,.png,.webp"
    >
      <n-button type="primary" v-bind="{ ...getButtonProps }"> 图片上传 </n-button>
    </NUpload>
  </div>
</template>
<script lang="ts">
import { defineComponent, computed } from 'vue';
import { NUpload } from 'naive-ui';
import SlashAppContext from '@/context/SlashAppContext';
import { UploadResponse } from '@/components/my-upload';

export default defineComponent({
  name: 'TinymceImageUpload',
  components: { NUpload },
  props: {
    fullscreen: {
      type: Boolean,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
  },
  emits: ['uploading', 'done', 'error'],
  setup(props, { emit }) {
    let uploading = false;
    const getButtonProps = computed(() => {
      const { disabled } = props;
      return {
        disabled,
      };
    });

    function handleChange(info: Recordable) {
      console.log(info);
      const file = info.file;
      const status = info.event.type;
      const name = file.Name;
      console.log('zhuangt', status);
      if (status === 'progress') {
        if (!uploading) {
          emit('uploading', name);
          uploading = true;
        }
      } else if (status === 'load') {
        const response: UploadResponse | null =
          info.event.target?.response && JSON.parse(info.event.target.response);
        const url = response?.data[0].url;
        emit('done', name, url);
        uploading = false;
      } else if (status === 'error') {
        emit('error');
        uploading = false;
      }
    }

    return {
      handleChange,
      getButtonProps,
      uploadUrl: SlashAppContext.getFileUploadUrl(),
    };
  },
});
</script>
<style lang="less" scoped>
.tinymce-img-upload {
  position: absolute;
  top: 5px;
  right: 10px;
  z-index: 20;

  &.fullscreen {
    position: fixed;
    z-index: 10000;
  }
}
</style>
